package com.itheima.controller;

import com.itheima.R;
import com.itheima.utils.AliOssUtil;
import com.itheima.vo.UploadVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@Slf4j
@RequestMapping("/common")
public class CommonController {
    @Autowired
    private AliOssUtil aliOssUtil;

    @PostMapping("/upload")
    public R upload(String type,MultipartFile file){
        log.info("..........{}",type);
        try {
            if(type.equals("images")){
                String originalFilename = file.getOriginalFilename();
                String prefix = originalFilename.substring(originalFilename.lastIndexOf("."));
                String newName = UUID.randomUUID().toString()+prefix;

                file.transferTo(new File("D:\\youdianda\\nginx-youdianda\\html\\backend\\undefined\\"+newName));
                UploadVO uploadVO = new UploadVO();
                uploadVO.setSavePath("/"+newName);
                uploadVO.setName(newName);
                uploadVO.setMime(file.getContentType());
                uploadVO.setSize(file.getSize());
                return R.success(uploadVO);
            }
        } catch (IOException e) {
            log.error("文件上传失败!");
        }
        return R.error("文件上传失败");
    }



    /*public R upload(MultipartFile file){
        try {
            String originalFilename = file.getOriginalFilename();
            String prefix = originalFilename.substring(originalFilename.lastIndexOf("."));
            String newName = UUID.randomUUID().toString()+prefix;
            String url = aliOssUtil.upload(file.getBytes(), newName);
            UploadVO uploadVO = new UploadVO();
            uploadVO.setSavaPath(url);
            uploadVO.setName(newName);
            uploadVO.setMime(file.getContentType());
            uploadVO.setSize(file.getSize());

            return R.success(uploadVO);

        } catch (IOException e) {
            log.error("文件上传失败");
        }
        return R.error("文件上传失败!");
    }*/
}
